#include "stm32f4xx.h"                  // Device header
#include "main.h"
#include <math.h>    //Keil library
#include <stdio.h>   //Keil library

#define	SlaveAddress   0x3C

unsigned char BUF[8];
int X,Y,Z;
double Angle_XY=0,Angle_XZ=0,Angle_YZ=0;

void Single_Write_HMC5883(unsigned char REG_Address,unsigned char REG_data)
{
    IIC_Start();
    IIC_Send_Byte(SlaveAddress);
    IIC_Send_Byte(REG_Address);
    IIC_Send_Byte(REG_data);
    IIC_Stop();
}

void Multiple_Read_HMC5883(void)
{
	unsigned char i;
    IIC_Start();
    IIC_Send_Byte(SlaveAddress);
    IIC_Send_Byte(0x03);
    IIC_Start();
    IIC_Send_Byte(SlaveAddress+1);
	for (i=0; i<6; i++)
    {
		BUF[i] = IIC_Read_Byte(0);
        if (i == 5)
        {
			IIC_NAck();
        }
        else
        {
			IIC_Ack();
		}
	}
	IIC_Stop();
	delay_ms(5);
}

void Init_HMC5883(void)
{
     Single_Write_HMC5883(0x00,0x70);
     Single_Write_HMC5883(0x01,0x20);
     Single_Write_HMC5883(0x02,0x00);
}

void Read_HMC5883_Data(void)
{
	Multiple_Read_HMC5883();
	
	X=BUF[0] << 8 | BUF[1]; //Combine MSB and LSB of X Data output register
	Z=BUF[2] << 8 | BUF[3]; //Combine MSB and LSB of Z Data output register
	Y=BUF[4] << 8 | BUF[5]; //Combine MSB and LSB of Y Data output register
	
	if(X>0x7fff)X-=0xffff;
	if(Y>0x7fff)Y-=0xffff;
	if(Z>0x7fff)Z-=0xffff;
	
	Angle_XY= atan2((double)Y,(double)X) * (180 / 3.14159265) + 180;
	Angle_XY*=10;
	
	Angle_XZ= atan2((double)Z,(double)X) * (180 / 3.14159265) + 180;
	Angle_XZ*=10;
	
	Angle_YZ= atan2((double)Z,(double)Y) * (180 / 3.14159265) + 180;
	Angle_YZ*=10;
	Single_Write_HMC5883(0x00,0x70);
	Single_Write_HMC5883(0x02,0x00);
}
